//app.js
const request = require("/libs/request.js");
const QQMapWX = require("/libs/qqmap-wx-jssdk.min.js");
const config = require("/config/index.js");
const { generateUrlQuerystring } = require("/utils/util.js");
let locationInstance = null;
App({
  onLaunch: function (options) {
    console.log(options);
    //加载配置
    this.globalData.$config = config;
    //地图
    locationInstance = new QQMapWX({
      key: config.MAP_KEY
    });
    this.globalData.$locationInstance = locationInstance;
    
    //初始化相关storage值
    let token = wx.getStorageSync("DT-TOKEN")
    let userinfo = wx.getStorageSync("DT-USERINFO");
    if(token && userinfo){
      this.globalData.userinfo = userinfo;
      this.globalData.token = token;
    }
    //获取系统信息
    this.getSysInfo();
    //
    //this.getUserScope();
  },
  onShow: function (options){
    console.log("app show get scene");
    let scene = options.scene;
    this.globalData.shareScene = false;
    //分享场景
    if(scene == 1007){
      this.globalData.shareScene = true;  
    }
    console.log(options);
    let locationInfo = wx.getStorageSync("DT-LOCATION-INFO");
    let city = wx.getStorageSync("DT-CITY");
     //if(!locationInfo || !city){
       //this.getLocation();
     //}
  },
  globalData: {
  },
  getSysInfo(){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.globalData.deviceInfo = res;
        that.globalData.platform = res.platform;
        that.globalData.statusBarHeight = res.statusBarHeight
        that.globalData.titleBarHeight = 46;//默认设置46
      },
      failure() {
        that.globalData.statusBarHeight = 0
        that.globalData.titleBarHeight = 0
      }
    })
  },
  getUserScope(){
    // 获取用户信息
    const _this = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          // wx.getUserInfo({
          //   success: res => {
          //     // 可以将 res 发送给后台解码出 unionId
          //     this.globalData.userInfo = res.userInfo

          //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          //     // 所以此处加入 callback 以防止这种情况
          //     if (this.userInfoReadyCallback) {
          //       this.userInfoReadyCallback(res)
          //     }
          //   }
          // })
        }
        if (!res.authSetting['scope.userLocation']) {
          console.log("auth user location");
          wx.authorize({
            scope: "scope.userLocation",
            success:() => {
              this.getLocation();
            },
            fail:()=>{
              wx.setStorageSync("DT-CITY", "深圳");
            }
          });
        }
      }
    })
  },
  getLocation(){
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success:(res) => {
        let latitude = res.latitude;
        let longitude = res.longitude;
        locationInstance.reverseGeocoder({
          location: {
            latitude,
            longitude
          },
          success(res){
            console.log(res);
            let result = res.result;
            const locationInfo = {
              ...result.ad_info
            };
            _this.globalData.locationInfo = locationInfo;
            wx.setStorageSync("DT-LOCATION-INFO", locationInfo);
            wx.setStorageSync("DT-CITY",locationInfo.city.replace("市",""));
            _this.globalData.city = locationInfo.city;
          },
          fail(res){
            console.log(res);
          }
        })
      }
    })
  },
  /**
   * 校验是否登录
   */
  checkLogin(){
    let token = wx.getStorageSync("DT-TOKEN") || "";
    let userInfo = wx.getStorageSync("DT-USERINFO") || {};
    if(!token || !Object.keys(userInfo).length){
      let pages = getCurrentPages();
      let currentPage = pages[pages.length-1];
      let options = currentPage.options;
      let refer = encodeURIComponent(`/${currentPage.route}?${generateUrlQuerystring(options)}`);
      wx.redirectTo({
        url: `/pages/login/index?refer=${refer}`,
      });
      return false;
    }
    return true;
  },
  checkIsTab(path){
    const tabs = ["/pages/index/index", "/pages/invite/index", "/pages/message/index", "/pages/mine/index","/pages/release/index"];
     return tabs.find(v => path.startsWith(v)) || false;
  },
  isLogin(){
    let token = wx.getStorageSync("DT-TOKEN") || "";
    let userInfo = wx.getStorageSync("DT-USERINFO") || {};
    if (!token || !Object.keys(userInfo).length) {
      let pages = getCurrentPages();
      let currentPage = pages[pages.length - 1];
      let options = currentPage.options;
      return false;
    }
    return true;
  }
})